package com.cyou.dream.core;

import com.cyou.dream.logging.LogMarkers;
import lombok.extern.log4j.Log4j2;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Log4j2
public class ScriptRegistry {
    private static final String SCRIPT_DIR = "classpath:lua/";
    private static final Map<String, RedisScript<Long>> scriptCache = new ConcurrentHashMap<>();

    @PostConstruct
    public void initScripts() throws IOException {
        Resource[] resources = new PathMatchingResourcePatternResolver()
                .getResources(SCRIPT_DIR + "*.lua");

        for (Resource resource : resources) {
            String scriptName = resource.getFilename();
            String scriptContent = StreamUtils.copyToString(
                    resource.getInputStream(), StandardCharsets.UTF_8);

            RedisScript<Long> script = RedisScript.of(scriptContent, Long.class);
            scriptCache.put(scriptName, script);
            log.info(LogMarkers.DreamRiskEngine, "Loaded script: {}", scriptName);
        }
    }

    public static RedisScript<Long> getScript(String scriptName) {
        return Optional.ofNullable(scriptCache.get(scriptName))
                .orElseThrow(() -> new IllegalArgumentException("Script not found: " + scriptName));
    }
}
